package com.shigu.postFee.service;

import com.opentae.data.mall.beans.MallPostfee;
import com.opentae.data.mall.examples.MallPostfeeExample;
import com.opentae.data.mall.interfaces.MallPostfeeMapper;
import com.shigu.MallResponse;
import com.shigu.PageResponse;
import com.shigu.exceptions.AdminException;
import com.shigu.postFee.bo.AddPostModelBo;
import com.shigu.postFee.bo.ModifyPostModelBo;
import com.shigu.postFee.enums.PostFeeType;
import com.shigu.postFee.vo.FeeModelVo;
import com.shigu.postFee.vo.PostModelVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PostFeeService {
    @Autowired
    MallPostfeeMapper mallPostfeeMapper;

    /**
     * @description 添加商品是查找运费模板
     * @author 郭尔
     * @date 2019/1/13 10:33
     */
    public PageResponse<PostModelVo> postFeeModel() {
        MallPostfeeExample example = new MallPostfeeExample();
        example.createCriteria().andFatherIdEqualTo(-1l);
        List<MallPostfee> list = mallPostfeeMapper.selectByExample(example);

        PageResponse<PostModelVo> response = new PageResponse<>();
        response.setData(list.stream().map(o -> {
            PostModelVo vo = new PostModelVo();
            vo.setFeeId(o.getFeeId());
            vo.setName(o.getName());
            return vo;
        }).collect(Collectors.toList()));
        return response.success();
    }

    /**
     * @description 添加运费模板
     * @author 郭尔
     * @date 2019/1/13 11:08
     */
    public MallResponse addPostFeeModel(AddPostModelBo bo) {
        MallPostfee father = new MallPostfee();
        father.setName(bo.getName());
        father.setType(bo.getType().getValue());
        if (bo.getType().getValue() != PostFeeType.FREE.getValue()) {
            //类型不是包邮时
            father.setFee(bo.getFee());
            father.setLimitNum(bo.getLimit());
            father.setIncrease(bo.getIncrease());
            father.setIncreaseFee(bo.getIncreaseFee());
        }
        mallPostfeeMapper.insertSelective(father);
        if (bo.getSonType()!=null) {
            //指定地区为子模板
            MallPostfee son = new MallPostfee();
            son.setFatherId(father.getFeeId());
            son.setName(bo.getName());
            son.setProvIds(bo.getProvIds());
            son.setType(bo.getSonType().getValue());
            if (bo.getSonType().getValue() != PostFeeType.FREE.getValue()) {
                //类型不是包邮时
                son.setFee(bo.getSonFee());
                son.setLimitNum(bo.getSonLimit());
                son.setIncrease(bo.getSonIncrease());
                son.setIncreaseFee(bo.getSonIncreaseFee());
            }
            mallPostfeeMapper.insertSelective(son);
        }
        return new MallResponse().success();
    }
    /**
     *
     * @description
     * @author 郭尔
     * @date 2019/1/18 18:25
     */
    public MallResponse modifyPostFeeModel(ModifyPostModelBo bo){
        MallPostfee father = new MallPostfee();
        father.setFeeId(bo.getFeeId());
        father.setName(bo.getName());
        father.setType(bo.getType().getValue());
        if (bo.getType().getValue() != PostFeeType.FREE.getValue()) {
            //类型不是包邮时
            father.setFee(bo.getFee());
            father.setLimitNum(bo.getLimit());
            father.setIncrease(bo.getIncrease());
            father.setIncreaseFee(bo.getIncreaseFee());
        }else {
            father.setFee(0d);
            father.setLimitNum(0);
            father.setIncrease(0);
            father.setIncreaseFee(0d);
        }
        mallPostfeeMapper.updateByPrimaryKeySelective(father);

        MallPostfee son = mallPostfeeMapper.selectByFatherId(bo.getFeeId());
        if(son == null){
            son = new MallPostfee();
        }

        if (bo.getSonType()!=null) {//有指定省份
            //含有指定地区为子模板
            son.setFatherId(bo.getFeeId());
            son.setName(bo.getName());
            son.setProvIds(bo.getProvIds());
            son.setType(bo.getSonType().getValue());
            if (bo.getSonType().getValue() != PostFeeType.FREE.getValue()) {
                //类型不是包邮时
                son.setFee(bo.getSonFee());
                son.setLimitNum(bo.getSonLimit());
                son.setIncrease(bo.getSonIncrease());
                son.setIncreaseFee(bo.getSonIncreaseFee());
            }else {
                son.setFee(0d);
                son.setLimitNum(0);
                son.setIncrease(0);
                son.setIncreaseFee(0d);
            }
            if(son.getFeeId()==null){
                mallPostfeeMapper.insertSelective(son);
            }else {
                mallPostfeeMapper.updateByPrimaryKeySelective(son);
            }
        }


        return new MallResponse().success();
    }
    /**
     * @description 运费模板列表
     * @author 郭尔
     * @date 2019/1/13 12:05
     */
    public PageResponse<FeeModelVo> postModelList() {
        MallPostfeeExample example = new MallPostfeeExample();
        example.createCriteria().andFatherIdEqualTo(-1l);
        List<MallPostfee> list = mallPostfeeMapper.selectByExample(example);
        PageResponse<FeeModelVo> response = new PageResponse<>();
        response.setData(list.stream().map(o -> {
            FeeModelVo vo = new FeeModelVo();

            vo.setType(o.getType());
            vo.setName(o.getName());
            vo.setFeeId(o.getFeeId());
            vo.setFee(o.getFee());
            vo.setIncrease(o.getIncrease());
            vo.setLimit(o.getLimitNum());
            vo.setIncreaseFee(o.getIncreaseFee());
            MallPostfee son = mallPostfeeMapper.selectByFatherId(o.getFeeId());
            if (son != null) {
                vo.setProvIds(Arrays.asList(son.getProvIds().split(",")));
                vo.setSonType(son.getType());
                if (son.getType() != PostFeeType.FREE.getValue()) {
                    vo.setSonFee(son.getFee());
                    vo.setSonLimit(son.getLimitNum());
                    vo.setSonIncrease(son.getIncrease());
                    vo.setSonIncreaseFee(son.getIncreaseFee());
                }
            }
            return vo;
        }).collect(Collectors.toList()));


        return response.success();
    }

    /**
     *
     * @description 删除运费模板
     * @author 郭尔
     * @date 2019/1/18 15:10
     */
    public MallResponse deletePostModel(Long feeId) throws AdminException {
        List<String> codes = mallPostfeeMapper.getUseItem(feeId);
        if(codes.size()>0){
            String itemCodes = StringUtils.join( codes.iterator(), ",");
            throw new AdminException("商品："+itemCodes+"使用该模板中，不能删除");
        }
        mallPostfeeMapper.deleteByPrimaryKey(feeId);
        return new MallResponse().success();

    }

    /**
     * @param weight 单件商品的重量
     * @param num    商品数量
     * @param feeId  运费模板id
     * @param provId 目标省id
     * @description 根据运费模板计算运费
     * @author 郭尔
     * @date 2019/1/13 13:11
     */
    public double postFee(int weight, long feeId, int num, long provId) {
        double fee;
        //先查询是否为指定模板的省份
        MallPostfee son = mallPostfeeMapper.checkProvFee(provId, feeId);
        if (son != null) { //省份是该模板指定的特殊计费省份
            fee = calculateFee(weight, num, son.getLimitNum(), son.getIncreaseFee(), son.getFee(), son.getIncrease(), son.getType());
        } else {
            MallPostfee post = mallPostfeeMapper.selectByPrimaryKey(feeId);
            fee = calculateFee(weight, num, post.getLimitNum(), post.getIncreaseFee(), post.getFee(), post.getIncrease(), post.getType());
        }
        return fee;
    }

    /**
     * @description 计算运费
     * @author 郭尔
     * @date 2019/1/13 13:56
     */
    public double calculateFee(int weight, int num, int limit, double increaseFee, double fee, int increase, int type) {
        switch (type) {
            case 1:
                if (num > limit) {
                    Integer amountFee =  (int) ( ((num - limit) / increase ) * increaseFee);
                    fee += amountFee;//多余的数量/单位增量 * 每单位的所需费用
                    int flag = (num - limit) % increase > 0 ? 1 : 0; //不足的部分往上取
                    fee += flag * increaseFee;
                }
                break;
            case 2:
                if (num * weight > limit) {
                    Integer amountFee =  (int)( ((num * weight - limit) / increase) * increaseFee );
                    fee += amountFee; //多余的数量/单位增量 * 每单位的所需费用
                    int flag = (num * weight - limit) % increase > 0 ? 1 : 0; //不足的部分往上取
                    fee += flag * increaseFee;
                }
                break;
            case 3:
                fee = 0.00;
                break;
        }
        return fee;
    }
}
